/**
 * Description：返工返修 hooks
 * Copyright (c) : 通力凯顿（北京）系统集成有限公司
 * Writer：朱楠
 * date: 2024.8.19
 */
const { ref, reactive } = Vue
import { useFetch } from '../../../Scripts/hooks/useFetch.js'
const { ElMessage, ElMessageBox } = ElementPlus
import { useCommon } from '../useCommon.js';

export function useRework() {
  const baseAPI = '../../../Ashx/ContainerReworkVue3PageHandler.ashx';

  const { generateUUID } = useCommon();
  let currentUserInfo = {};// 当前登录用户信息

  const reworkObjFormRef = ref(null);//表单ref
  const reworkReasonFormRef = ref(null);//返修原因维护表单ref
  const reworkReasonTableRef = ref(null);//返修原因维护表格ref

  const reworkObj = reactive({
    dialogVisible: false,
    tabObj: { historyTab: 'historyTab', reworkTab: 'reworkTab', },
    // 表单
    form: {
      containerid: '',
      containername: '',
      productid: '',
      productname: '',
      productdesc: '',
      workflowstepname: '',
      workflowstepid: '',
      workflowid: '',
      mfgordername: '',
      reworkNo: '',//返修编号
      checker: '',//检验员
      discoverDept: '',//发现单位
      qty: 0,//在制数
      reworkSum: 0,//已返工数
      dutyDept: '',//责任单位
      dutyEmp: '',//责任人
      changNo: '',//更改单号
    },
    historyDataList: [],//返工返修历史数据
    reworkInfoDataList: [],//返修原因表格数据
    lossReasonList: [],//返修原因
    // 表单校验
    formRules: {
      changNo: [
        { required: true, message: '【更改单号】不能为空', trigger: 'blur' },
      ],
      dutyDept: [
        { required: true, message: '【责任单位】不能为空', trigger: 'blur' },
      ],
      dutyEmp: [
        { required: true, message: '【责任人】不能为空', trigger: 'blur' },
      ]
    },
    // 返工原因维护--表单
    reworkResonForm: {
      reworkQty: 1,//返修数
      reworkReason: '',//返修原因
    },
    // 返工原因维护--表单校验规则
    reworkResonFormRules: {
      reworkQty: [
        { required: true, message: '【返修数】不能为空', trigger: 'blur' },
        { validator: validator, trigger: 'blur' }
      ],
      reworkReason: [
        { required: true, message: '【返工原因】不能为空', trigger: 'blur' },
      ],
    }
  });

  // 查询返修原因
  async function getLossReasonByGroupName() {
    const { data } = await useFetch({
      url: '../../../Ashx/FetchCommonHandler.ashx?actions=getLossReasonByGroupName',
      data: { type: 'getLossReasonByGroupName', lossreasongroupname: '返工原因组' }
    });
    reworkObj.lossReasonList = data.value;
  }

  // 查询返工编号
  async function getMaxStepReworkInfoNO() {
    // 返工编号格式为:F-年份-分厂代码-5位流水码
    const year = new Date().getFullYear();
    const factorycode = currentUserInfo.factorycode;
    const stepreworkinfono = `F-${year}-${factorycode}-`;
    const { data } = await useFetch({
      url: `${baseAPI}?actions=getMaxStepReworkInfoNO`,
      data: { type: 'getMaxStepReworkInfoNO', stepreworkinfono }
    });
    if (data.value.length === 0) {
      reworkObj.form.reworkNo = `F-${year}-${factorycode}-00001`;
    } else {
      const no = parseInt(data.value[0].stepreworkinfono.split('-')[3]) + 1;
      reworkObj.form.reworkNo = `F-${year}-${factorycode}-${no.toString().padStart(5, '0')}`;
    }
  }

  //查询已返工记录
  async function getHistoryReworkData() {
    const { containerid, workflowstepid } = reworkObj.form;
    const { data } = await useFetch({
      url: `${baseAPI}?actions=getHistoryReworkData`,
      data: { type: 'getHistoryReworkData', containerid, workflowstepid }
    });
    reworkObj.historyDataList = data.value;
    // 计算已返工总数
    reworkObj.form.reworkSum = data.value.reduce((current, item) => current + parseInt(item.reworkqty), 0);
  }

  // 自定义校验规则
  function validator(rule, value, callback) {
    if (/^\d+$/.test(value)) {
      callback();
    } else {
      callback(new Error('只能输入整数'));
    }
  }

  // 初始化数据
  async function initReworkDialogData(currentSelectContainer, selectionRows, userInfo, containerInfo) {
    reworkObj.dialogVisible = true;
    currentUserInfo = userInfo.value;
    const { workflowstepname, productid, productname, productdescription, workflowstepid, workcentername } = currentSelectContainer;
    const {
      containername, qty,
      containerid, mfgordername,
    } = selectionRows[0];

    reworkObj.form.containerid = containerid;
    reworkObj.form.containername = containername;
    reworkObj.form.productname = productname;
    reworkObj.form.productid = productid;
    reworkObj.form.productdesc = productdescription;
    reworkObj.form.workflowstepid = workflowstepid;
    reworkObj.form.workflowstepname = workflowstepname;
    reworkObj.form.mfgordername = mfgordername;
    reworkObj.form.qty = qty;
    reworkObj.form.checker = currentUserInfo.fullname;//检验员
    reworkObj.form.discoverDept = `${currentUserInfo.factoryname}检验室`;//发现单位
    reworkObj.form.dutyDept = workcentername;//责任单位
    reworkObj.form.dutyEmp = containerInfo.reportEmp;//责任人

    await getHistoryReworkData();
    await getLossReasonByGroupName();//查询返修原因
    await getMaxStepReworkInfoNO();//查询并给【返修编号】绑定值
  }

  // 返工原因【添加】按钮点击
  async function handleReworkAddClick() {
    try {
      await reworkReasonFormRef.value.validate();
      const { reworkReason } = reworkObj.reworkResonForm;
      reworkObj.reworkInfoDataList.push({
        id: generateUUID(),
        ...reworkObj.reworkResonForm,
        reworkReasonName: reworkObj.lossReasonList.filter(i => i.lossreasonid === reworkReason)[0].lossreasonname,
      });
      reworkReasonTableRef.value.toggleAllSelection();//勾选已有全部副产品行
      reworkReasonFormRef.value.resetFields();//重置副产品维护表单
    } catch (error) {
      return;
    }
  }

  // 返工原因【删除】按钮点击
  function handleReworkDeleteClick() {
    const selection = reworkReasonTableRef.value.getSelectionRows();
    if (selection.length === 0) { return ElMessage({ type: 'error', message: `请勾选要删除的数据`, grouping: true }); }
    reworkObj.reworkInfoDataList = reworkObj.reworkInfoDataList.filter(i => !selection.some(m => m.id === i.id));
  }

  // 重置对话框数据
  async function resetReworkDialogData() {
    reworkObjFormRef.value.resetFields();//重置表单数据
    reworkReasonFormRef.value.resetFields();//重置返修原因表单数据
    reworkObj.reworkInfoDataList = [];
  }

  // 【提交】按钮点击
  async function handleReworkSubmitClick() {
    if (!await validate()) { return; }
    ElMessageBox.confirm(`你确认要提交吗?`, '确认', { type: 'warning' }).then(async () => {
      const selection = reworkReasonTableRef.value.getSelectionRows();
      const { data, status: { msg } } = await useFetch({
        url: `${baseAPI}?actions=saveData`,
        data: {
          type: 'saveData',
          employeename: currentUserInfo.employeename,
          reworkDataList: selection,
          ...reworkObj.form
        }
      });
      if (data.value === true) {
        ElMessage({ type: 'success', message: `保存成功`, grouping: true });
        await getHistoryReworkData();
        await getMaxStepReworkInfoNO();
        reworkObj.reworkInfoDataList = [];//清空返修原因表格数据
        reworkObj.form.changNo = '';
      } else {
        ElMessage({ type: 'error', message: msg, grouping: true });
      }
    }).catch(() => {
      ElMessage({ type: 'info', message: '已取消' });
    });
  }

  async function validate() {
    try {
      await reworkObjFormRef.value.validate();
      if (reworkObj.reworkInfoDataList.length === 0) {
        ElMessage({ type: 'error', message: `请先添加返工原因信息`, grouping: true });
        return false;
      }

      const selections = reworkReasonTableRef.value.getSelectionRows();
      if (selections.length === 0) {
        ElMessage({ type: 'error', message: `请勾选返修原因`, grouping: true });
        return false;
      }

      const { reworkSum, qty } = reworkObj.form;
      const reworkQty = selections.reduce((current, item) => current + parseInt(item.reworkQty), 0);
      if (reworkQty + reworkSum > qty) {
        ElMessage({ type: 'error', message: `返工返修总数不能大于${qty}`, grouping: true });
        return false;
      }

    } catch (error) {
      return false;
    }

    return true;
  }

  return {
    reworkObj,
    reworkObjFormRef,
    initReworkDialogData,
    reworkObjFormRef,//表单ref
    reworkReasonFormRef,//返修原因维护表单ref
    reworkReasonTableRef,//返修原因维护表格ref
    handleReworkAddClick,//返修原因维护【添加】按钮点击
    handleReworkDeleteClick,//返修原因维护【删除】按钮点击
    handleReworkSubmitClick,//【提交】按钮点击
    resetReworkDialogData,//重置返修表单数据
  };
}